﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Web.Script.Serialization;

namespace Eksponent.CropUp
{
    public class CropInfo
    {
        /// <summary>
        /// The top left corner of the crop rectangle
        /// </summary>
        public PointF TopLeft { get; set; }

        /// <summary>
        /// The bottom right corner of the crop rectangle
        /// </summary>
        public PointF BottomRight { get; set; }

        /// <summary>
        /// The bias point in the crop rectangle. This point will be centered if cropping within the rectangle is needed.
        /// If not specified, the image within the crop rectangle will never be cropped.        
        /// </summary>        
        public PointF? Gravity { get; set; }

        [Obsolete("Use gravity instead")]
        public PointF? Bias { get { return Gravity; } set { Gravity = value; } }

        /// <summary>
        /// Is the crop info automatically calculated?
        /// </summary>        
        public bool Calculated { get; set; }

        /// <summary>
        /// Use relative coordinates, i.e. percentages?
        /// </summary>
        public bool Relative { get; set; }

        public CropInfo ToAbsolute(int width, int height)
        {
            if (!Relative) return this;

            var info = new CropInfo();
            info.Relative = false;
            info.TopLeft = new PointF(TopLeft.X * width, TopLeft.Y * height);
            info.BottomRight = new PointF(BottomRight.X * width, BottomRight.Y * height);
            info.Gravity = Gravity != null ? new PointF(Gravity.Value.X * width, Gravity.Value.Y * height) : (PointF?)null;
            info.Calculated = Calculated;

            return info;
        }

        public CropInfo ToRelative(int width, int height)
        {
            if (Relative) return this;

            var info = new CropInfo();
            info.Relative = true;
            info.TopLeft = new PointF(TopLeft.X / width, TopLeft.Y / height);
            info.BottomRight = new PointF(BottomRight.X / width, BottomRight.Y / height);
            info.Gravity = Gravity != null ? new PointF(Gravity.Value.X / width, Gravity.Value.Y / height) : (PointF?)null;
            info.Calculated = Calculated;

            return info;
        }

        public static CropInfo Default
        {
            get
            {
                var ci = new CropInfo()
                    {
                        Relative = true,
                        Calculated = true,
                        Gravity = new PointF(.5f, .5f)
                    };
                return ci;
            }
        }


        public CropInfo()
        {
            Relative = true;
            TopLeft = new PointF(0, 0);
            BottomRight = new PointF(1, 1);            
        }
    }
}